package com.example.mybaseapp.ui

import android.Manifest
import android.app.AppOpsManager
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Process
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.mybaseapp.R
import com.example.mybaseapp.bean.ImageData


class PictureActivity : AppCompatActivity() {
    private val SELECT_IMAGE_AND_VIDEO_CODE = 20
    private val REQUEST_RECORD_AUDIO_PERMISSION = 22

//    private lateinit var  imageAdapter:ImageAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_picture)
        initView()
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun initView() {
        findViewById<Button>(R.id.btn).apply {
            setOnClickListener {
                var intent = Intent(Intent.ACTION_PICK)
                intent.type = "video/*, image/*"
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                startActivityForResult(intent, SELECT_IMAGE_AND_VIDEO_CODE)
            }
        }

        findViewById<Button>(R.id.btn2).apply {
            setOnClickListener {
                var intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.type = "video/*, image/*"
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                startActivityForResult(Intent.createChooser(intent, "选择图片"), SELECT_IMAGE_AND_VIDEO_CODE)
            }
        }
        findViewById<Button>(R.id.btn3).apply {
            setOnClickListener {
//                if (!checkManageExternalStoragePermission()){
//                    askManage()
//                }else{
//                    getImages()
//                }

                getImages()
//                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MANAGE_EXTERNAL_STORAGE).forEach { it1 ->
//                    if (ActivityCompat.checkSelfPermission(
//                            this@PictureActivity,
//                            it1
//                        )
//                        != PackageManager.PERMISSION_GRANTED
//                    ) {
//                        ActivityCompat.requestPermissions(
//                            this@PictureActivity,
//                            arrayOf(it1),
//                            REQUEST_RECORD_AUDIO_PERMISSION
//                        )
//                    } else {
//                        // 权限已授权，可以开始录音
//                        getImages()
//                    }
//                }
            }
        }
    }

    private fun askManage(){
        Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION).apply {
            startActivityForResult(this, REQUEST_RECORD_AUDIO_PERMISSION)
        }
    }

    // 检查应用是否持有MANAGE_EXTERNAL_STORAGE权限
    private fun checkManageExternalStoragePermission(): Boolean {
        val appOpsManager = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager?
        if (appOpsManager == null) {
            return false // 如果无法获取AppOpsManager实例，则认为权限未被授予
        }
        val mode = appOpsManager.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_EXTERNAL_STORAGE, Process.myUid(),
            null.toString()
        ) // 检查权限状态，返回值代表不同的权限级别（例如是否已授权等）
        return mode == AppOpsManager.MODE_ALLOWED // 如果返回值是MODE_ALLOWED，则代表已经获得权限
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            REQUEST_RECORD_AUDIO_PERMISSION->{
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限获得
                    getImages()
                } else {
                    // 权限拒绝，提示用户
                    Toast.makeText(this, "权限获取失败，请手动设置权限。", Toast.LENGTH_SHORT).show()
                }

            }
        }
    }

    private fun getImages() {
        val projection = arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME)
        val cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null)

//        val images = mutableListOf<ImageData>() // ImageData 是你自己的数据类
        cursor?.use {
            Log.d("Fire", "getImages: ${it.count}")
//            val idColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
//            val nameColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
//
//            while (it.moveToNext()) {
//                val id = it.getLong(idColumn)
//                val name = it.getString(nameColumn)
//                val contentUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
//                images.add(ImageData(id, name, contentUri.toString()))
//            }
        }

        // 更新 RecyclerView
//        findViewById<RecyclerView>(R.id.recyclerview).apply {
//            imageAdapter = ImageAdapter(images) { selectedImage ->
//                handleImageSelection(selectedImage)
//            }
//            adapter = imageAdapter
//        }
    }

//    private fun handleImageSelection(selectedImage: ImageData) {
//        // 多选
//        val selectedImages = imageAdapter.getSelectedImages()
//
//        // 单选
//        if (selectedImages.size == 1) {
//            val uri = selectedImages.first().contentUri
//            // 处理单张图片
//        } else if (selectedImages.size > 1) {
//            // 处理多张图片
//        }
//    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            SELECT_IMAGE_AND_VIDEO_CODE->{
                data.apply {

                }
            }
            SELECT_IMAGE_AND_VIDEO_CODE->{

            }

            REQUEST_RECORD_AUDIO_PERMISSION->{
                getImages()
            }
        }
    }
}